import React, { Component } from "react";
import { connect } from "dva";
import {
  Form,
  Input,
  Button,
  Icon,
  Breadcrumb,
  Table,
  Modal,
  Tree,
  notification,
  TreeSelect,
  message,
  Alert,

} from "antd";
import lodash from "lodash";
import { gup } from "../../../utils/utils";
import AddDepartment from "./AddDepartment";
import EditDepartment from "./EditDepartment";
import GetPlanBook from "./getPlanBook";

import "./less/depart.less";
// import * as ajax from "../../../services/api";
import {
  systemComDepartPage, //部门人员分页功能
  systemComDepartSave, //部门新增-添加子部
  //systemComDepartTreeComDepart, //查询公司及部门的树形结构
  systemComDepartDelete, //删除部门功能
  getTreeDepart, //选择部门
  getTreeperBydepart, //选择人员
  systemComDepartAdjustDepart, //调整部门人员
  systemComDepartBatchInsertDepart, //部门批量操作功能
  systemComDepartUpdateLeaveDate, //部门批量离职----误报错误有使用-----
  getOnlineInsBlbLink,
  comInsGetComInsPage, //保全分页
  enterpriseInsComInsGetOnlineInsBlbPreservationLink, //生成保全
  enterpriseInsComInsSaveBookScheme, //保存方案书
  enterpriseInsComInsPromptInitEnterpriseIns, //是否需要保险提示
  // enterpriseInsComInsPromptCompanyInitGen,//温馨提示图片地址
} from "../../../services/api";

const { confirm } = Modal;
const { Search } = Input;
const { TreeNode } = Tree;

// const { MenuItemGroup } = Menu;
@connect(state => ({
  profile: state.profile,
  global: state.global
}))
@Form.create()

/**
 * 部门管理组件
 */
export default class DepartmentManagement extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      perIds: "",
      dataSource: [],
      modelInit: gup("model"),
      otherbook: gup("otherbook"),
      selectedRows: [], //选中的行
      selectedRowKeys: [], //选中的行key
      AddDepartmentVisible: false,
      EditDepartmentVisible: false,
      selectDepartmentVisible: false,
      searchValue: "",
      pos: "0-0",
      dataList: [],
      expandedKeys: [],
      selectedKeys: [],
      newDepartId: "",
      treeData: [
        //树
        { title: "", key: "", personCount: "" }
      ],
      treeDataSearch: [{ title: "", key: "" }],
      /**
       * 抽屉需要
       */
      placeholder: "请输入关键字",
      title: "", //当前标题
      departId: "-1", //部门id
      chidrens: [],
      tableData: [],
      pagenav: {
        current: 1,
        pageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: total => `总共 ${total} 条`,
        onShowSizeChange: (current, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = current;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav });
          setTimeout(() => {
            this.systemComDepartPage();
          });
        },
        onChange: (page, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = page;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav });
          setTimeout(() => {
            this.systemComDepartPage();
          });
        },
        total: 0
      },
      reducepeoplevisible: false,
      visible: false,
      insurancetipsvisible: false, //提示模板
      onlineUrl: "", //购买在线保险的url
      accessbookvisible: false, //获取方案书
      isIns: "",
      // comName:"",//企业名称
    };
  }

  componentDidMount() {
    this.getTreeDepart();
    //this.getTreeperBydepart();
    this.getTreeperBydepart();
    this.systemComDepartPage("-1");
    //初始化参数，修复页面切换参数不会初始化的bug！！
    this.messageOnline();
    this.getPrimotInt();
    this.getotherbook();
    this.comInsGetComInsPage();
  }

  // 保险员减员提示
  showreducepeopleModal = () => {
    this.setState({
      reducepeoplevisible: true
    });
  };

  handlereducepeopleOk = () => {
    this.setState({
      reducepeoplevisible: false,
      // 订单大于1，选择订单
      visible: true
    });
  };
  handlereducepeopleCancel = () => {
    this.setState({
      reducepeoplevisible: false
    });
  };
  // 选择订单
  showModal = () => {
    this.setState({
      visible: true
    });
  };
  handleOk = () => {
    this.setState({
      visible: false
    });
  };
  handleCancel = () => {
    this.setState({
      visible: false
    });
  };
  // 温馨提示
  showsurancetipsModal = () => {
    this.setState({
      insurancetipsvisible: true
    });
  };
  handlesuranceOk = e => {
    console.log(e);
    this.setState({
      insurancetipsvisible: false,
      accessbookvisible: true
    });
  };
  handleonline = e => {
    console.log(e);
    this.setState({
      insurancetipsvisible: false,
    });
    window.open(this.state.onlineUrl);
  };
  handlesurancetipxCancel = e => {
    console.log(e);
    this.setState({
      insurancetipsvisible: false
      // insurancetipvisible:true,
    });
  };
  handlesurancetipCancel = e => {
    console.log(e);
    this.setState({
      // insurancetipvisible: false,
      insurancetipsvisible: false
    });
    this.props.history.push(
      // 跳转到1-4-4
      "/enterprise/company"
    );
  };
  // 获取方案书
  showaccessbookModal = () => {
    this.setState({
      accessbookvisible: true
    });
  };
  handlenextpeopleOk = e => {
    //获取方案书表单提交
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log("方案书values", values);
        console.log("Id", this.state.currentId);
        const obj = {
          contactper: values.contactper ? values.contactper : "",
          contactPhone: values.contactPhone ? values.contactPhone : "",
          comPerNum: values.comPerNum ? values.comPerNum : "",
          guaranteeAmountLow: values.guaranteeAmountLow
            ? values.guaranteeAmountLow
            : "",
          insAmountUp: values.insAmountUp ? values.insAmountUp : "",
          proCode: ""
        };
        console.log("方案书信息obj", obj);
        enterpriseInsComInsSaveBookScheme(obj).then(
          res => {
            console.log("成功信息-方案书values", res);
            // message.success("保存成功！");
          },
          error => {
            message.error(error);
            console.log("错误信息-方案书values", error);
          }
        );
        this.props.re;
        this.setState({
          accessbookvisible: false
        });
      }
    });
  };
  handlereducepeopleCancel = e => {
    console.log(e);
    this.setState({
      accessbookvisible: false,
      insurancetipsvisible: false
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log("表单提交中.........", values);
      }
    });
  };

  handleproductCancel = e => {
    console.log(e);
    this.setState({
      accessbookvisible: true
    });
  };
  showsurancetipModal = () => {
    this.setState({
      // insurancetipvisible: true,
    });
  };
  //在线购买保险的链接生成
  messageOnline = () => {
    getOnlineInsBlbLink({
      comId: this.props.global.companyInfo.comId
    }).then(data => {
      this.setState({
        onlineUrl: data.data
      });
    });
  };

  // 初始化温馨提示
  getPrimotInt = () => {
    enterpriseInsComInsPromptInitEnterpriseIns({}).then(data => {
      console.log("是否初始化", data);
      this.setState({
        isIns: data.data.isIns
      });
      if (this.state.modelInit === "init") {
        this.setState({
          insurancetipsvisible: true
        });
      }
    });
  };
  // 温馨提示初始化图片
  // getImgInt = () => {
  //   enterpriseInsComInsPromptCompanyInitGen({}).then(data => {
  //     console.log("温馨提示初始化图片", data.data);
  //     // this.setState({
  //     //   isIns: data.data.isIns
  //     // });
  //   });
  // };
  // 选择其他产品
  getotherbook = () => {
    if (this.state.otherbook === "init") {
      this.setState({
        accessbookvisible: true
      });
    }
  };
  checkPhone = (rule, value, callback) => {
    if (value && !/^1[0-9]{10}$/.test(value)) {
      callback("请输入正确的手机号码！");
    } else {
      callback();
    }
  };
  checkpeoplenum = (rule, value, callback) => {
    if (value && !/^[0-9]*$/.test(value)) {
      callback("请输入数字！");
    } else {
      callback();
    }
  };
  // 温馨提示马上查看
  rightCheckClick = () => {
    this.props.history.push(`/insurancemanagement/enterpriseinsurance`);
  };
  //保存方案书
  // saveBookSchema = () => {
  //   enterpriseInsComInsSaveBookScheme({}).then(data => {
  //     // this.setState({
  //     //   onlineUrl: data.data
  //     // });
  //     setTimeout(() => {
  //       console.log("保存方案书",data);
  //     },500);
  //   });
  // };
  comInsGetComInsPage = () => {
    const { pagenav } = this.state;
    comInsGetComInsPage({
      pageSize: pagenav.pageSize,
      pageNumber: pagenav.current,
      buyMode: "1"
    })
      .then(res => {
        console.log(res, "保险分页-res");
        const dataSource = res.data.data.map(val => {
          val.key = val.blbOrderId;
          return val;
        });
        this.setState({ dataSource });
      })
      .catch(err => console.log(err));
  };

  //保险选择
  renderTable = () => {
    const rowSelection = {
      type: "radio",
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: selectedRowKeys => {
        this.setState({ selectedRowKeys });
      },
      getCheckboxProps: record => ({
        disabled: record.name === "Disabled User" // Column configuration not to be checked
      })
    };
    const columns = [
      {
        title: "订单号",
        dataIndex: "blbOrderId",
        key: "blbOrderId"
      },
      {
        title: "保险产品",
        dataIndex: "insComName",
        key: "insComName"
      },
      {
        title: "人数",
        dataIndex: "perNum",
        key: "perNum"
      },
      {
        title: "购买时间",
        dataIndex: "effectStartDate",
        key: "effectStartDate"
      }
    ];

    return (
      <Table
        size="middle"
        width={800}
        rowSelection={rowSelection}
        columns={columns}
        pagination={false}
        dataSource={this.state.dataSource}
      />
    );
  };

  //保全链接生成
  enterpriseInsComInsGetOnlineInsBlbPreservationLink() {
    enterpriseInsComInsGetOnlineInsBlbPreservationLink({
      orderId: this.state.selectedRowKeys,
      perIds: this.state.perIds,
      reviseType: "2"
    })
      .then(res => {
        console.log(res, "保全链接生成-res");
        this.setState({ visible: false });
        window.open(res.data);
        this.newwin.location.href = res.data;
      })
      .catch(err => console.log(err, "保全链接生成-err"));
  }

  /* 搜索----------------start */

  onChange = e => {
    const { value } = e.target;
    let { treeData } = this.state;
    const { treeDataSearch } = this.state;
    if (value.trim().length > 0) {
      treeData = treeDataSearch;
    }

    console.log(this.state.dataList, "this.state.dataList");
    let expandedKeys = this.state.dataList
      .map(item => {
        if (item.title.indexOf(value) > -1) {
          return this.getParentKey(item.key, treeData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    if (value.trim().length === 0) {
      expandedKeys = [treeData[0].key];
    }
    console.log(expandedKeys, "expandedKeys");
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true
    });
  };

  getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (this.getParentKey(key, node.children)) {
          parentKey = this.getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  generateList = data => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title } = node;
      this.state.dataList.push({ key, title });
      if (node.children) {
        this.generateList(node.children, node.key);
      }
    }
  };

  /* 搜索 ---------------end*/

  //部门人员分页功能
  systemComDepartPage = departId => {
    systemComDepartPage({
      pageSize: 5000,
      pageNumber: 1,
      departId: departId || this.state.departId
    }).then(
      response => {
        console.log(response, "systemComDepartPage--response-部门人员分页功能");
        const tableData = response.data.data.map((val, i) => {
          val.key = i;
          return val;
        });
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.total = response.data.total;
        this.setState({
          tableData,
          selectedRows: [],
          selectedRowKeys: [],
          pagenav
        });
      },
      err => {
        console.log(err, "systemComDepartPage-err-部门人员分页功能s");
      }
    );
  };

  //部门新增-添加子部门
  systemComDepartSave = () => {
    systemComDepartSave({
      departName: "",
      perID: "",
      parentDepartId: ""
    }).then(
      response => {
        console.log(
          response,
          "systemComDepartSave--response-部门更新--编辑保存"
        );
        this.setState({ tableData: this.state.data });
      },
      err => {
        console.log(err, "systemComDepartSave-err-部门更新--编辑保存");
      }
    );
  };

  //删除树结点
  splicTreeNode = () => {
    const { treeData } = this.state;
    const posArr = this.state.pos.split("-").slice(1);
    if (posArr.length === 2) {
      treeData[posArr[0]].children.splice(posArr[1], 1);
    }
    if (posArr.length === 3) {
      treeData[posArr[0]].children[posArr[1]].children.splice(posArr[2], 1);
    }
    if (posArr.length === 4) {
      treeData[posArr[0]].children[posArr[1]].children[
        posArr[2]
      ].children.splice(posArr[3], 1);
    }
    this.setState({
      treeData,
      title: treeData[0].title,
      pos: "0-0"
    });
  };

  //获取你节点
  getParentNode = () => {
    const { treeData } = this.state;
    const posArr = this.state.pos.split("-").slice(1);
    let parentNode = treeData[0];
    if (posArr.length === 3) {
      parentNode = treeData[posArr[0]].children[posArr[1]];
    }
    if (posArr.length === 4) {
      parentNode = treeData[posArr[0]].children[posArr[1]].children[posArr[2]];
    }
    return parentNode;
  };

  // 删除部门功能
  systemComDepartDelete = () => {
    systemComDepartDelete({ departId: this.state.departId }).then(
      response => {
        console.log(response, "systemComDepartDelete--response-删除部门功能");
        notification["success"]({
          message: "删除部门成功"
        });
        this.setState({ EditDepartmentVisible: false, departId: "-1" });
        this.splicTreeNode();
      },
      err => {
        console.log(err, "systemComDepartDelete-err- 删除部门功能");
      }
    );
  };
  //生成当前树的位置
  generateTreeDataPosition = (treeData, pos) => {
    return treeData.map((val, i) => {
      const newObj = val;
      if (newObj.children && newObj.children.length > 0) {
        newObj.children = this.generateTreeDataPosition(
          newObj.children,
          `${pos}-${i}`
        );
      }
      newObj.pos = `${pos}-${i}`;
      return newObj;
    });
  };

  //选择部门
  getTreeDepart = () => {
    getTreeDepart({}).then(
      response => {
        console.log(response, "getTreeDepart-选择部门-response");
        let { data } = response;
        data = JSON.parse(
          JSON.stringify(data).replace(/\"children\":\[\]/g, '"isLeaf":true')
        );
        data = this.generateTreeDataPosition(data, "0");
        if (data.length > 0) {
          this.setState({
            treeData: data,
            chidrens: data[0].children,
            title: `${data[0].title}(${data[0]["personCount"]})`,
            departId: data[0].key,
            expandedKeys: [data[0].key],
            selectedKeys: [data[0].key]
          });
        }
      },
      err => {
        console.log(err, "getTreeDepart-选择部门-err");
      }
    );
  };

  generaUserData = (data, keyvalue) => {
    return data.map(val => {
      if (val.clildren && val.clildren.length > 0) {
        val.clildren.filter(val1 => {
          if (val1.title.indexOf(keyvalue) !== -1) {
            return true;
          } else {
            return false;
          }
        });
        return val;
      }
      return val;
    });
  };

  //选择人员
  getTreeperBydepart = () => {
    getTreeperBydepart({}).then(
      response => {
        console.log(response, "getTreeperBydepart-选择人员-response");
        let { data } = response;
        data = JSON.parse(
          JSON.stringify(data).replace(/\"children\":\"\"/g, '"isLeaf":true')
        );
        data = this.generateTreeDataPosition(data, "0");
        this.setState({
          treeDataSearch: data
        });
        this.generateList(data);
      },
      err => {
        console.log(err, "getTreeperBydepart-选择人员-err");
      }
    );
  };
  //部门批量操作功能
  systemComDepartBatchInsertDepart = () => {
    systemComDepartBatchInsertDepart({}).then(
      response => {
        console.log(
          response,
          "systemComDepartBatchInsertDepart-部门批量操作功能-response"
        );
      },
      err => {
        console.log(
          err,
          "systemComDepartBatchInsertDepart-部门批量操作功能-err"
        );
      }
    );
  };
  //调整部门人员
  systemComDepartAdjustDepart = () => {
    const perIds = [];
    let oldDepartId = "";
    const { selectedRows, newDepartId } = this.state;
    selectedRows.forEach(item => {
      perIds.push(item.perId);
      oldDepartId = item.departId || "";
    });

    systemComDepartAdjustDepart({
      perIds: JSON.stringify(perIds),
      oldDepartId,
      newDepartId
    }).then(
      response => {
        console.log(
          response,
          "systemComDepartAdjustDepart-调整部门人员-response"
        );
        this.getTreeDepart();
        this.systemComDepartPage();
      },
      err => {
        console.log(err, "systemComDepartAdjustDepart-调整部门人员-err");
      }
    );
  };

  //部门批量离职
  systemComDepartUpdateLeaveDate = () => {
    const perIds = [];
    this.state.selectedRows.forEach(val => {
      perIds.push(val.perId);
    });
    this.setState({ perIds: perIds.join(",") });
    systemComDepartUpdateLeaveDate({
      perIds: perIds.join(","),
      orgId: this.state.departId
    }).then(
      response => {
        console.log(
          response,
          "systemComDepartUpdateLeaveDate-部门批量离职-response"
        );
        this.setState({ selectedRows: [], selectedRowKeys: [] });
        this.systemComDepartPage();
        this.getTreeDepart();
      },
      err => {
        console.log(err, "systemComDepartUpdateLeaveDate-部门批量离职-err");
      }
    );
  };

  //渲染树
  renderTreeNodes = (data, parentkey, parentTitle) => {
    const { searchValue } = this.state;
    return data.map(val => {
      const item = JSON.parse(JSON.stringify(val).replace(/null/g, '""'));
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);
      let title = `${item.title}(${
        item.personCount === "" ? 0 : item.personCount
      })`;
      if (searchValue.trim().length > 0) {
        title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span style={{ color: "#f50" }}>{searchValue}</span>
              {`${afterStr}`}
            </span>
          ) : (
            <span>{`${item.title}`}</span>
          );
      }
      if (item.children) {
        return (
          <TreeNode
            parentkey={parentkey}
            parentTitle={parentTitle}
            treeType={item.treeType}
            realyTitle={item.title}
            key={item.key}
            title={title}
          >
            {this.renderTreeNodes(item.children, item.key, item.title)}
          </TreeNode>
        );
      }

      return (
        <TreeNode
          parentkey={parentkey}
          parentTitle={parentTitle}
          treeType={item.treeType}
          realyTitle={item.title}
          key={item.key}
          title={title}
        />
      );
    });
  };

  // 下级部门组别
  handleList = () => {
    if (this.state.chidrens !== "" && this.state.chidrens !== undefined) {
      return this.state.chidrens.map((val, i) => {
        if (val.treeType === "2") {
          return "";
        }
        return (
          <li
            onClick={() => {
              this.setState({
                chidrens:
                  val.children && val.children.length > 0 ? val.children : [],
                pos: val.pos,
                title: val.title,
                departId: val.key
              });
              this.systemComDepartPage(val.key);
            }}
            key={i}
          >
            <a>
              {val.title}({val.personCount ? val.personCount : 0})
              <Icon type="right" />
            </a>
          </li>
        );
      });
    }
  };

  //确定是否要删除部门
  showConfirm = () => {
    confirm({
      title: "提示",
      content: "请先移除当前部门下的人员，再删除当前部门！",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        this.systemComDepartDelete();
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  };
  //确定是否要离职
  withdrawnShowConfirm = () => {
    const mobiles = [];
    const name = [];
    this.state.selectedRows.forEach(val => {
      name.push(val.name);
      mobiles.push(val.mobilePhone);
    });
    console.log(
      this.state.selectedRows,
      "withdrawnShowConfirm-selectedRows-确定是否要离职"
    );
    if (mobiles.length === 0) {
      notification["warning"]({
        message: "请选择人员"
      });
      return;
    }
    confirm({
      title: "提示?",
      content: (
        <div
          dangerouslySetInnerHTML={{
            __html: `${name.join(",")}<br/>${mobiles.join(
              "<br/>"
            )}<br/>离职后将取消关联的任务及审批流程`
          }}
        />
      ),
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        this.systemComDepartUpdateLeaveDate();
        // 保险员减员提示
        if (this.state.dataSource.length > 0) {
          this.setState({
            reducepeoplevisible: true
          });
        }
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  };

  //部门人员表格
  renderDepartMan = () => {
    // 表格选择设置
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(
          `selectedRowKeys: ${selectedRowKeys}`,
          "selectedRows: ",
          selectedRows
        );
        this.setState({ selectedRows, selectedRowKeys });
      },
      getCheckboxProps: record => ({
        disabled: record.name === "Disabled User" // Column configuration not to be checked
      })
    };

    const columns = [
      {
        title: "姓名",
        dataIndex: "name",
        render: text => <div>{text}</div>
      },
      {
        title: "职位",
        dataIndex: "position"
      },
      {
        title: "工号",
        dataIndex: "jobNo"
      },
      {
        title: "手机号",
        dataIndex: "mobilePhone"
      },
      {
        title: "邮箱",
        dataIndex: "email"
      },
      {
        title: "状态",
        render: (text, record) => (
          <div>
            <span
              className={
                record.isAppActive === "1" ? "activated" : "inactivated"
              }
            >
              ·
            </span>
            <span className="status">
              {record.isAppActive === "1" ? "已激活" : "未激活"}
            </span>
          </div>
        )
      },
      {
        title: "操作",
        render: (text, record) => (
          <span
            style={{ color: "#108EE9", cursor: "pointer" }}
            onClick={() => {
              this.props.history.push(
                `/Organization/PersonnelInformationNav?perId=${record.perId}`
              );
            }}
          >
            修改
          </span>
        )
      }
    ];

    return (
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={this.state.tableData}
        pagination={this.state.pagenav}
      />
    );
  };

  //获取当前节点的子节点
  getPosChidrens = (target, data) => {
    return lodash.get(
      data,
      lodash.toPath(
        target
          .split("-")
          .slice(1)
          .map(p => `[${p}]`)
          .join(".children")
      )
    );
  };

  //保存编辑部门表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values, "handleSubmit-values");
      if (!err) {
        console.log("Received values of form: ", values);
      }
    });
  };

  getNodeDate = (treeData, index) => {
    const { pos } = this.state;
    let posArrs = pos.split("-");
    posArrs = posArrs.slice(1);
    for (let i = 0; i < index; i++) {
      if (i === 0) {
        return treeData[posArrs[i]];
      } else {
        return treeData[posArrs[i]];
      }
    }
  };

  //面包屑
  renderBread = () => {
    const { pos, searchValue, treeDataSearch } = this.state;
    let { treeData } = this.state;
    if (searchValue.trim().length > 0) {
      treeData = treeDataSearch;
    }
    const posArrs = pos.split("-");
    return posArrs.map((val, i) => {
      let nodeData = "";
      nodeData = this.getPosChidrens(
        posArrs.slice(0, i + 1).join("-"),
        treeData
      );
      if (i === 0) {
        return null;
      }
      return (
        <Breadcrumb.Item
          onClick={() => {
            if (i < posArrs.length - 1) {
              this.setState({
                pos: nodeData["pos"],
                title: `${nodeData["title"]}(${nodeData["personCount"]})`,
                departId: nodeData["key"],
                chidrens: nodeData["children"]
              });
              this.systemComDepartPage(nodeData["key"]);
            }
          }}
          key={i}
        >
          {i === posArrs.length - 1 ? nodeData.title : <a>{nodeData.title}</a>}
        </Breadcrumb.Item>
      );
    });
  };

  render() {
    //获取方案书
    const { treeDataSearch, treeData, searchValue } = this.state;
    let tree = treeData;
    if (searchValue.trim().length > 0) {
      tree = treeDataSearch;
    }
    return (
      <div className="DepartmentManagement">
        <div className="department-content">
          <div className="department-inquiry">
            <Search
              size="large"
              placeholder={this.state.placeholder}
              style={{ width: 200 }}
              onChange={this.onChange}
              maxLength="20"
            />
            <div className="depart-button">
              <Button
                onClick={() => {
                  this.props.history.push("/Organization/importexportNav");
                }}
              >
                批量导入
              </Button>
              <Button
                onClick={() => {
                  this.props.history.push("/Organization/resignationlist");
                }}
                className="button-right"
              >
                离职记录
              </Button>
            </div>
            <div className="depart-menu">
              {/* 查询下级部门功能 */}
              <Tree
                expandedKeys={this.state.expandedKeys}
                autoExpandParent={this.state.autoExpandParent}
                selectedKeys={this.state.selectedKeys}
                onExpand={expandedKeys => {
                  this.setState({ expandedKeys, autoExpandParent: false });
                }}
                onSelect={(selectedKeys, e) => {
                  console.log(selectedKeys, e, "selectedKeys-e");
                  if (
                    selectedKeys.length === 0 ||
                    e.selectedNodes.length === 0
                  ) {
                    return;
                  }
                  let departId = selectedKeys[0];
                  let { pos, realyTitle } = e.node.props;
                  const { parentTitle, parentkey } = e.node.props;
                  if (e.node.props.treeType === "2") {
                    departId = parentkey;
                    realyTitle = parentTitle;
                    pos = e.node.props.pos
                      .split("-")
                      .slice(0, -1)
                      .join("-");
                  }
                  this.systemComDepartPage(departId);
                  const treeNode = this.getPosChidrens(pos, tree);
                  console.log("...realyTitle....", realyTitle);
                  this.setState({
                    title: `${realyTitle.split("(")[0]}(${
                      treeNode["personCount"]
                    })`,
                    departId,
                    selectedKeys,
                    pos,
                    chidrens: treeNode["children"]
                  });
                }}
              >
                {this.renderTreeNodes(
                  tree,
                  [tree[0].key],
                  [tree[0].title],
                  [tree[0].personCount]
                )}
              </Tree>
            </div>
          </div>
          <div className="department-demonstrate">
            <div className="demonstrate-head">
              <p className="title">
                <span>{this.state.title}</span>
                {this.state.departId === "-1" ||
                this.state.departId === undefined ? (
                  ""
                ) : (
                  <Button
                    size="small"
                    onClick={() => {
                      this.setState({ EditDepartmentVisible: true });
                    }}
                  >
                    编辑
                  </Button>
                )}
              </p>
              <Breadcrumb>{this.renderBread()}</Breadcrumb>
            </div>
            <div className="demonstrate-line" />
            <div className="subordinate-departments">
              <div className="sub-title">
                <i />
                <span>下级部门</span>
              </div>
              <Button
                type="primary"
                icon="plus"
                onClick={() => this.setState({ AddDepartmentVisible: true })}
              >
                添加子部门
              </Button>
              <div className="depart-list">
                <ul>{this.handleList()}</ul>
              </div>
              <div className="sub-title division-title">
                <i className="division" />
                <span>部门人员</span>
              </div>
              <div className="division-button">
                <Button
                  onClick={() => {
                    this.props.history.push(
                      "/Organization/PersonnelInformationNav"
                    );
                  }}
                  type="primary"
                  icon="plus"
                >
                  添加成员
                </Button>
                <Button
                  onClick={() => {
                    if (this.state.selectedRows.length === 0) {
                      notification["error"]({
                        message: "请选择人员"
                      });
                      return;
                    }

                    this.setState({ selectDepartmentVisible: true });
                  }}
                >
                  调整部门
                </Button>
                <Button
                  type="danger"
                  ghost
                  onClick={() => {
                    if (this.state.selectedRows.length === 0) {
                      notification["error"]({
                        message: "请选择人员"
                      });
                      return;
                    }
                    this.withdrawnShowConfirm();
                  }}
                >
                  批量离职
                </Button>
              </div>
              <div className="division-table">{this.renderDepartMan()}</div>
            </div>
          </div>
        </div>

        <Modal
          title="选择部门"
          visible={this.state.selectDepartmentVisible}
          onOk={() => {
            if (this.state.newDepartId === "") {
              notification["error"]({
                message: "请选择新的部门"
              });
              return;
            }
            this.setState({ selectDepartmentVisible: false });
            this.systemComDepartAdjustDepart();
          }}
          onCancel={() => {
            this.setState({ selectDepartmentVisible: false });
          }}
        >
          <TreeSelect
            value={this.state.newDepartId}
            style={{ width: 300 }}
            dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
            treeData={this.state.treeData}
            placeholder="请选择部门"
            treeDefaultExpandAll
            onChange={newDepartId => {
              console.log(newDepartId, "TreeSelect-newDepartId");
              this.setState({ newDepartId });
            }}
          />
        </Modal>

        {/* 弹出添加子部门-抽屉 */}
        <AddDepartment
          treeData={this.state.treeData}
          departId={this.state.departId}
          open={this.state.AddDepartmentVisible}
          addSuccess={() => {
            this.getTreeDepart();
          }}
          ok={open => {
            this.setState({ AddDepartmentVisible: open });
          }}
        />
        {/* 弹出编辑部门-抽屉 */}
        <EditDepartment
          treeData={this.state.treeData}
          departId={this.state.departId}
          open={this.state.EditDepartmentVisible}
          delete={this.showConfirm}
          editSuccess={() => {
            this.getTreeDepart();
          }}
          ok={open => {
            this.setState({ EditDepartmentVisible: open });
          }}
        />
        {/* 保险员减员提示 */}
        <Modal
          className="reducepeople"
          title="保险员减员提示"
          visible={this.state.reducepeoplevisible}
          onOk={this.handlereducepeopleOk}
          onCancel={this.handlereducepeopleCancel}
          footer={[
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                this.setState({
                  reducepeoplevisible: false,
                  visible: true
                });
              }}
            >
              马上办理
            </Button>
          ]}
        >
          <div>
            <div>
              <Alert
                message="保险产品的增员、减员、替换等操作可通过【金融保险】-【保险订单】-选择有效订单的【保全】对保单中的人员增减操作！"
                type="warning"
                showIcon
              />
            </div>
            <p>
              本次离职人员共 %s 位，[保险日期]已为其中%s
              位员工购买过团意险产品[产品名称]（订单号：[订单编号]），企业可对离职人员办理保险保全的减员操作，以降低保险成本！
            </p>
          </div>
        </Modal>
        {/* 订单大于1时，选择订单 */}
        <Modal
          className="chooseorderlist"
          title="选择订单"
          visible={this.state.visible}
          onOk={() => {
            if (!this.state.selectedRowKeys) {
              message.error("请选择订单");
              return null;
            }
            this.newwin = window.open("about:blank");
            this.enterpriseInsComInsGetOnlineInsBlbPreservationLink();
          }}
          onCancel={this.handleCancel}
        >
          <Alert
            message="当前企业所购买了多份团意险产品。请选择需要增员/减员的订单:"
            type="success"
            showIcon
          />
          {this.renderTable()}
        </Modal>
        {/* 初始化是弹窗 */}
        <GetPlanBook
          okorcancel={(field, value) => {
            this.setState({ [field]: value });
          }}
          isIns={this.state.isIns}
          accessbookvisible={this.state.accessbookvisible}
          insurancetipsvisible={this.state.insurancetipsvisible}
        />
      </div>
    );
  }
}
